<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/5/28
 * Time: 下午6:33
 */

namespace EasySwoole\EasySwoole;


use App\Storage\ChatMessageFile;
use App\Storage\OnlineUser;
use App\WebSocket\WebSocketEvents;
use App\WebSocket\WebSocketParser;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\FastCache\Cache;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\MysqliPool\Mysql;
use EasySwoole\Socket\Dispatcher;
use EasySwoole\EasySwoole\Config as GConfig;
use EasySwoole\RedisPool\Config as RConfig;
use EasySwoole\Mysqli\Config as MConfig;
use EasySwoole\RedisPool\Redis;

class EasySwooleEvent implements Event
{

    public static function initialize()
    {
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');

        // 注册redis pool
        $configData = GConfig::getInstance()->getConf('REDIS');
        $config = new RConfig($configData);
        $poolConf = Redis::getInstance()->register('redis',$config);
        $poolConf->setMaxObjectNum($configData['maxObjectNum']);
        $poolConf->setMinObjectNum($configData['minObjectNum']);

        // 注册mysql pool
        $mysqlConfigData = GConfig::getInstance()->getConf('MYSQL');
        $mysqlConfig = new MConfig($mysqlConfigData);
        $mysqlPoolConf = Mysql::getInstance()->register('mysql',$mysqlConfig);
        $mysqlPoolConf->setMaxObjectNum($configData['maxObjectNum']);
        $mysqlPoolConf->setMinObjectNum($configData['minObjectNum']);
    }

    public static function mainServerCreate(EventRegister $register)
    {
        $server = ServerManager::getInstance()->getSwooleServer();

        OnlineUser::getInstance();
        ChatMessageFile::getInstance();
        Cache::getInstance()->setTempDir(EASYSWOOLE_ROOT . '/Temp')->attachToServer($server);

        // 注册服务事件
        $register->add(EventRegister::onOpen,[WebSocketEvents::class, 'onOpen']);
        $register->add(EventRegister::onClose,[WebSocketEvents::class, 'onClose']);

        // 收到用户消息时处理
        $conf = new \EasySwoole\Socket\config;
        $conf->setType($conf::WEB_SOCKET);
        $conf->setParser(new WebSocketParser());
        $dispatch = new Dispatcher($conf);
        $register->set(EventRegister::onMessage,function (\swoole_server $server, \swoole_websocket_frame $frame) use ($dispatch) {
           $dispatch->dispatch($server, $frame->data, $frame);
        });

        // TODO: Implement mainServerCreate() method.
    }

    public static function onRequest(Request $request, Response $response): bool
    {
        // TODO: Implement onRequest() method.
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        // TODO: Implement afterAction() method.
    }
}